package com.panda.compile;

import com.panda.common.ResourceHolder;
import com.panda.pojo.Context;
import com.panda.utils.ParseUtils;
import com.panda.utils.PrePostUtils;
import lombok.Getter;
import lombok.Setter;

import java.io.PrintStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;


@Setter
@Getter
public class Compiler {

    private ResourceHolder resourceHolder;

    public Compiler(ResourceHolder resourceHolder) {
        this.resourceHolder = resourceHolder;
    }

    public void compile() {

        try {
            resourceHolder.handle();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //根上下文,该上下文中包含所有必要的css,js,component,service,command等等可以复用的内容
        Context context = new Context();

        context.setConfig(resourceHolder.getConfig());

        context.getJsFiles().putAll(resourceHolder.getJs());
        context.getCssFiles().putAll(resourceHolder.getCss());

        //开始解析之前要进行预处理,包括配置文件的处理,对css和js文件的处理等
        PrePostUtils.pre(context, resourceHolder);

        Map<String, PrintStream> pandas = resourceHolder.getPandas();
        //编译panda文件
        pandas.forEach((s, printStream) -> {

            Context nc = new Context(context, s);

            nc.setControllerScopes(new HashSet<>());

            nc.setStringMap(new LinkedHashMap<>());

            compile(nc, pandas.get(s));
        });

    }

    private void compile(Context context, PrintStream output) {

        //开始解析
        ParseUtils.parse(context, resourceHolder);

        //把上下文以文本输出
        output.println(context.toString());

        //System.out.println(context.toString());

        //关流
        output.close();

    }

}
